﻿namespace Summoner
{
    using UnityEngine;
    using System;
    using System.Collections.Generic;
#if UNITY_EDITOR
    using UnityEditor;
    using System.Linq;
#endif

    [Serializable]
    public class AtlasObject : ScriptableObject
    {
        [SerializeField]
        public List<Sprite> tileSprites = new List<Sprite>();
        [NonSerialized]
        private Dictionary<string, Sprite> _name2sprite = new Dictionary<string, Sprite>();
        [SerializeField]
        private UnityEngine.Object _spriteObject = null;

#if UNITY_EDITOR
        public void Init()
        {
            if (this.tileSprites.Count == 0)
            {
                Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(this.SpriteObject)).OfType<Sprite>().ToArray();
                this.tileSprites.Clear();
                for (int i = 0; i < sprites.Length; i++)
                {
                    this.tileSprites.Add(sprites[i]);
                }
            }
        }
#endif

        public Sprite GetSprite(string name)
        {
            if (this.Name2Sprite.ContainsKey(name))
            {
                return this.Name2Sprite[name];
            }
            return null;
        }

        public Dictionary<string, Sprite> Name2Sprite
        {
            get
            {
#if UNITY_EDITOR
                this.Init();
#endif
                if(this._name2sprite.Count == 0)
                {
                    tileSprites.ForEach(o => this._name2sprite[o.name] = o);
                }
                return this._name2sprite;
            }
        }

        public UnityEngine.Object SpriteObject
        {
            get { return this._spriteObject; }
            set { this._spriteObject = value; }
        }
    }
}